import React, { useState } from 'react';
import { TabBar } from './TabBar';
import { AddressBar } from './AddressBar';
import { BrowserView } from './BrowserView';
import { useBrowser } from '../hooks/useBrowser';

export function BrowserLayout() {
  const { activeTab, addTab, navigationState, setNavigationState } = useBrowser();
  const [currentUrl, setCurrentUrl] = useState('https://www.google.com');

  const handleNewTab = () => {
    addTab();
  };

  const handleNavigate = (url: string) => {
    setCurrentUrl(url);
    setNavigationState(prev => ({ ...prev, isLoading: true }));
    
    // 模拟页面加载
    setTimeout(() => {
      setNavigationState(prev => ({ ...prev, isLoading: false }));
    }, 1000);
  };

  const handleRefresh = () => {
    setNavigationState(prev => ({ ...prev, isLoading: true }));
    setTimeout(() => {
      setNavigationState(prev => ({ ...prev, isLoading: false }));
    }, 500);
  };

  const handleHome = () => {
    handleNavigate('https://www.google.com');
  };

  if (!activeTab) {
    return (
      <div className="w-full h-full flex flex-col">
        <TabBar onNewTab={handleNewTab} />
        <div className="flex-1 flex items-center justify-center bg-gray-100">
          <button
            onClick={handleNewTab}
            className="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
          >
            新建标签页
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full h-full flex flex-col">
      <TabBar onNewTab={handleNewTab} />
      <AddressBar
        url={currentUrl}
        onNavigate={handleNavigate}
        onRefresh={handleRefresh}
        onHome={handleHome}
        canGoBack={navigationState.canGoBack}
        canGoForward={navigationState.canGoForward}
      />
      <div className="flex-1 relative">
        <BrowserView
          url={currentUrl}
          isLoading={navigationState.isLoading}
        />
      </div>
    </div>
  );
}